#include "audio_data.h"
#include "adpcm.h"
#include "device.h"

/* 调试打印接口 */
#define AUDIO_DATA_LOG(format, ...)    __OSAL_LOG(format, ##__VA_ARGS__)

/**
  * @brief  获取语音信息
  * @note   
  */
ErrorStatus Audio_GetInfo(uint16_t audioIndex, SoundInfo_stu_t *soundInfo, uint8_t *flag)
{
	uint32_t offsetAddr = audioIndex * 8 + 8;
	if(audioIndex == 0)
	{
		return ERROR;
	}

    uint8_t data[8];
    Device_Read(vFLASH_0, data, 8, 8);
    if(strcmp((const char *)data,"pcm") == 0)
    {
        AUDIO_DATA_LOG("pcm audio file\r\n");
        *flag = 1;
    }
    else
    {
        AUDIO_DATA_LOG("adpcm audio file\r\n");
        *flag = 0;
    }

	Device_Read(vFLASH_0, soundInfo, sizeof(SoundInfo_stu_t), offsetAddr);
	return SUCCESS;
}

/**
  * @brief  读取音乐数据，并解码成16位wav
  * @note   启动播放时，一次性填充2个buf
  *         
  * @param  pBuf:解析后的数据
  * @param  flashAddr: ADPCM数据地址
  * @param  readSize: 读取数据的字节数
  */
void Audio_ReadAdpcmAndDecode(uint8_t *pBuf, uint32_t flashAddr, uint16_t readSize)
{
	uint16_t i;
	int16_t sound;

    uint8_t *audioDataBufferTemp = OSAL_Malloc(readSize);
    if(audioDataBufferTemp == NULL)
    {
        AUDIO_DATA_LOG("audioDataBuffer malloc error\r\n");
        return;
    }
    Device_Read(vFLASH_0, audioDataBufferTemp, readSize, flashAddr);
    for(i = 0;i < readSize; i++)
    {
        sound = ADPCM_Decode(audioDataBufferTemp[i] & 0x0f);
        *pBuf++ = (uint8_t)(sound & 0x00ff);
        *pBuf++ = (uint8_t)((sound >> 8));
    
        sound =  ADPCM_Decode(audioDataBufferTemp[i] >> 4);
        *pBuf++ = (uint8_t)(sound & 0x00ff);
        *pBuf++ = (uint8_t)((sound >> 8));
    }
    OSAL_Free(audioDataBufferTemp);
}

